package org.testis.wirelesssecuritymodule.core;

import org.testis.data.TestStepDataObject;
import org.testis.threading.TaskExecutor;
import org.testis.wirelesssecuritymodule.data.WirelessSecurityModuleDataObject;

/**
 *
 * @author nurhat
 */
public class WirelessConnectionTaskExecutor {

    TaskExecutor m_threadExecutorPool;
    public static WirelessConnectionTaskExecutor m_wirelessConnectionTaskExecutor;

    /**
     * Creates a task executor and initalize thread pool
     */
    private WirelessConnectionTaskExecutor() {
        m_threadExecutorPool = new TaskExecutor(40,
                40,
                200,
                200);
    }

    public static WirelessConnectionTaskExecutor getInstance() {
        if (m_wirelessConnectionTaskExecutor == null) {
            m_wirelessConnectionTaskExecutor =
                    new WirelessConnectionTaskExecutor();
        }
        return m_wirelessConnectionTaskExecutor;
    }

    /**
     * Any task can be added to thread pool over this method.
     * @param data
     */
    public final void executeTask(TestStepDataObject dObj) {

        if (!dObj.isStopExecution()) {
            runTask(dObj);
        } else {
            cancelTask(dObj);
        }

    }

    /**
     * Running task for the given ssid
     * @param data
     */
    private final void runTask(TestStepDataObject dObj) {
        String className = super.getClass().getSimpleName();
        try {
            WirelessConnectionSupplier task = WirelessConnectionProviderFactory.getInstance(
                    (WirelessSecurityModuleDataObject) dObj);
            m_threadExecutorPool.addTask(task);
        } catch (Exception ex) {
        } finally {
        }
    }

    /**
     * Cancelling running task for the given ssid
     * @param data
     */
    private final void cancelTask(TestStepDataObject dObj) {
        WirelessSecurityModuleDataObject mDO = (WirelessSecurityModuleDataObject) dObj;
        m_threadExecutorPool.cancelTask(mDO.getNicGuid());

    }

    public void abortAllTasks(Boolean abortAll) {
        if (abortAll) {
            m_threadExecutorPool.abortAllTasks();
        }
    }

    /**
     * Closes thread pool
     * @throws java.lang.Throwable
     */
    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        if (m_threadExecutorPool != null) {
            m_threadExecutorPool.shutdown();
            m_threadExecutorPool = null;
        }
    }
}
